package com.example.project10;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * 书籍数据访问对象
 * 提供对书籍数据的增删改查操作
 */
public class BookDao {
    private BookDatabaseHelper dbHelper;
    private SQLiteDatabase db;

    public BookDao(Context context) {
        dbHelper = new BookDatabaseHelper(context);
    }

    public void open() {
        db = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }
    
    /**
     * 添加书籍
     */
    public long addBook(Book book) {
        ContentValues values = new ContentValues();
        values.put(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER, book.getBookNumber());
        values.put(DatabaseContract.BookEntry.COLUMN_BOOK_NAME, book.getBookName());
        values.put(DatabaseContract.BookEntry.COLUMN_USER_EMAIL, book.getUserEmail());
        
        return db.insert(DatabaseContract.BookEntry.TABLE_BOOKS, null, values);
    }
    
    /**
     * 删除书籍
     */
    public int deleteBook(int bookId, String userEmail) {
        String selection = DatabaseContract.BookEntry.COLUMN_ID + "=? AND " +
                          DatabaseContract.BookEntry.COLUMN_USER_EMAIL + "=?";
        String[] selectionArgs = {String.valueOf(bookId), userEmail};
        
        return db.delete(DatabaseContract.BookEntry.TABLE_BOOKS, selection, selectionArgs);
    }
    
    /**
     * 更新书籍信息
     */
    public int updateBook(Book book) {
        ContentValues values = new ContentValues();
        values.put(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER, book.getBookNumber());
        values.put(DatabaseContract.BookEntry.COLUMN_BOOK_NAME, book.getBookName());
        
        String selection = DatabaseContract.BookEntry.COLUMN_ID + "=? AND " +
                          DatabaseContract.BookEntry.COLUMN_USER_EMAIL + "=?";
        String[] selectionArgs = {String.valueOf(book.getId()), book.getUserEmail()};
        
        return db.update(DatabaseContract.BookEntry.TABLE_BOOKS, values, selection, selectionArgs);
    }
    
    /**
     * 查询指定用户的所有书籍
     */
    public List<Book> getAllBooksByUser(String userEmail) {
        List<Book> books = new ArrayList<>();
        
        String selection = DatabaseContract.BookEntry.COLUMN_USER_EMAIL + "=?";
        String[] selectionArgs = {userEmail};
        
        Cursor cursor = db.query(DatabaseContract.BookEntry.TABLE_BOOKS, null,
                               selection, selectionArgs, null, null, null);
        
        if (cursor.moveToFirst()) {
            do {
                Book book = new Book();
                book.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_ID)));
                book.setBookNumber(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER)));
                book.setBookName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NAME)));
                book.setUserEmail(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_USER_EMAIL)));
                books.add(book);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        return books;
    }
    
    /**
     * 根据书号查询书籍
     */
    public List<Book> searchBooksByNumber(String bookNumber, String userEmail) {
        List<Book> books = new ArrayList<>();
        
        String selection = DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER + " LIKE ? AND " +
                          DatabaseContract.BookEntry.COLUMN_USER_EMAIL + "=?";
        String[] selectionArgs = {"%" + bookNumber + "%", userEmail};
        
        Cursor cursor = db.query(DatabaseContract.BookEntry.TABLE_BOOKS, null,
                               selection, selectionArgs, null, null, null);
        
        if (cursor.moveToFirst()) {
            do {
                Book book = new Book();
                book.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_ID)));
                book.setBookNumber(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER)));
                book.setBookName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NAME)));
                book.setUserEmail(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_USER_EMAIL)));
                books.add(book);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        return books;
    }
    
    /**
     * 根据书名查询书籍
     */
    public List<Book> searchBooksByName(String bookName, String userEmail) {
        List<Book> books = new ArrayList<>();
        
        String selection = DatabaseContract.BookEntry.COLUMN_BOOK_NAME + " LIKE ? AND " +
                          DatabaseContract.BookEntry.COLUMN_USER_EMAIL + "=?";
        String[] selectionArgs = {"%" + bookName + "%", userEmail};
        
        Cursor cursor = db.query(DatabaseContract.BookEntry.TABLE_BOOKS, null,
                               selection, selectionArgs, null, null, null);
        
        if (cursor.moveToFirst()) {
            do {
                Book book = new Book();
                book.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_ID)));
                book.setBookNumber(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER)));
                book.setBookName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NAME)));
                book.setUserEmail(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_USER_EMAIL)));
                books.add(book);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        return books;
    }
    
    /**
     * 根据书号和书名同时查询
     */
    public List<Book> searchBooks(String bookNumber, String bookName, String userEmail) {
        if ((bookNumber == null || bookNumber.trim().isEmpty()) && 
            (bookName == null || bookName.trim().isEmpty())) {
            // 如果都为空，返回该用户所有书籍
            return getAllBooksByUser(userEmail);
        }
        
        List<Book> books = new ArrayList<>();
        
        StringBuilder selectionBuilder = new StringBuilder();
        List<String> selectionArgsList = new ArrayList<>();
        
        if (bookNumber != null && !bookNumber.trim().isEmpty()) {
            selectionBuilder.append(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER).append(" LIKE ?");
            selectionArgsList.add("%" + bookNumber.trim() + "%");
        }
        
        if (bookName != null && !bookName.trim().isEmpty()) {
            if (selectionBuilder.length() > 0) {
                selectionBuilder.append(" AND ");
            }
            selectionBuilder.append(DatabaseContract.BookEntry.COLUMN_BOOK_NAME).append(" LIKE ?");
            selectionArgsList.add("%" + bookName.trim() + "%");
        }
        
        selectionBuilder.append(" AND ").append(DatabaseContract.BookEntry.COLUMN_USER_EMAIL).append("=?");
        selectionArgsList.add(userEmail);
        
        String[] selectionArgs = selectionArgsList.toArray(new String[0]);
        
        Cursor cursor = db.query(DatabaseContract.BookEntry.TABLE_BOOKS, null,
                               selectionBuilder.toString(), selectionArgs, null, null, null);
        
        if (cursor.moveToFirst()) {
            do {
                Book book = new Book();
                book.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_ID)));
                book.setBookNumber(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NUMBER)));
                book.setBookName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_BOOK_NAME)));
                book.setUserEmail(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.BookEntry.COLUMN_USER_EMAIL)));
                books.add(book);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        return books;
    }
}